`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2022/09/04 11:41:22
// Design Name: 
// Module Name: station
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module station(
    input clk,
    input rst,
    input valid_s,
    input [3:0] data_s,
    input ready_d,
    output valid_d,
    output [3:0] data_d,
    output reg ready_s
    );
    
    wire handshake;
    wire store_data;
    reg valid_buffer;
    reg [3:0] buffer;
    
    assign handshake = ready_s && valid_s;
    assign store_data = handshake && ~ready_d;
    assign valid_d = ready_s ? valid_s : valid_buffer;
    assign data_d  = ready_s ? data_s  : buffer;
    
    always @(posedge clk)
    begin
        if (rst) 
        begin
            valid_buffer <= 1'b0;
        end
        else
        begin
            valid_buffer <= valid_buffer ? ~ready_d: store_data;
        end
    end
    
    always @(posedge clk)
    begin
        if (rst) 
        begin
            ready_s <= 1;
        end
        else
        begin
            ready_s <= ready_d || ((~valid_buffer) && (~store_data));
        end
    end 
    
    always @(posedge clk)
    begin
        if (rst) 
        begin
            buffer <= 0;
        end
        else
        begin
            buffer <= store_data ? data_s : buffer;
        end
    end                



endmodule

